var TodoList = (function () {
    let tasks = JSON.parse(localStorage.getItem('tasks')) || [
        { id: 1, text: "睡觉", completed: false },
        { id: 2, text: "吃饭", completed: true },
        { id: 3, text: "打豆豆", completed: false }
    ];

    function saveToLocalStorage() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }

    function renderTasks(filteredTasks) {
        const ul = document.querySelector(".tasklist ul");
        ul.innerHTML = '';
        filteredTasks.forEach(task => {
            const li = document.createElement('li');
            li.innerHTML = `<div class="left">
                            <input type="checkbox" data-id="${task.id}" ${task.completed ? 'checked' : ''}>
                            <span class="${task.completed ? 'line' : ''}">${task.text}</span>
                          </div>
                          <div class="btn-group">
                            <button class="editBtn" data-id="${task.id}">编辑</button>
                            <button class="delBtn" data-id="${task.id}">删除</button>
                          </div>`;
            ul.appendChild(li);
        });
        updateCount();
    }

    function addTask(text) {
        const newTask = { id: tasks.length > 0 ? tasks[tasks.length - 1].id + 1 : 1, text: text, completed: false };
        tasks.push(newTask);
        saveToLocalStorage();
        renderTasks(tasks);
    }

    function removeTask(id) {
        tasks = tasks.filter(task => task.id != id);
        saveToLocalStorage();
        renderTasks(tasks);
    }

    function editTask(id, newText) {
        const task = tasks.find(t => t.id == id);
        if (task) {
            task.text = newText;
            saveToLocalStorage();
            renderTasks(tasks);
        }
    }

    function changeStatus(id, completed) {
        const task = tasks.find(t => t.id == id);
        if (task) {
            task.completed = completed;
            saveToLocalStorage();
            renderTasks(tasks);
        }
    }

    function filterTasks(filter) {
        switch (filter) {
            case "completed": return tasks.filter(task => task.completed);
            case "uncompleted": return tasks.filter(task => !task.completed);
            default: return tasks;
        }
    }

    function updateCount() {
        let all = tasks.length;
        let completed = tasks.filter(task => task.completed).length;
        let uncompleted = all - completed;

        document.querySelector('.footer span:nth-child(1)').textContent = `全部 ${all}`;
        document.querySelector('.footer span:nth-child(2)').textContent = `已完成 ${completed}`;
        document.querySelector('.footer span:nth-child(3)').textContent = `未完成 ${uncompleted}`;
    }

    return {
        addTask: addTask,
        removeTask: removeTask,
        editTask: editTask,
        changeStatus: changeStatus,
        filterTasks: filterTasks,
        renderTasks: renderTasks
    };
})();